import cv2
import numpy as np

def ShamirReconstruction(shares, k):
    """
    使用拉格朗日插值法重建秘密
    :param shares: 份额列表，每个份额是一个 (x, y) 对
    :param k: 阈值，需要 k 个份额才能重建秘密
    :return: 重建的秘密值
    """
    x = np.array([shares[i][0] for i in range(k)])
    y = np.array([shares[i][1] for i in range(k)])

    def lagrange_basis(x, j):
        """计算拉格朗日基多项式 L_j(0)"""
        numerator = np.prod([0 - x[m] for m in range(k) if m != j])
        denominator = np.prod([x[j] - x[m] for m in range(k) if m != j])
        return numerator / denominator

    s = 0
    for i in range(k):
        s += y[i] * lagrange_basis(x, i)
    return int(s)

# 读取任意两个份额图像（8位格式）
fx1 = cv2.imread('share_1.bmp', cv2.IMREAD_GRAYSCALE)
fx2 = cv2.imread('share_2.bmp', cv2.IMREAD_GRAYSCALE)

# 获取图像尺寸
h, w = fx1.shape

# 初始化重建图像（8位灰度图像）
recovered_image = np.zeros((h, w), dtype=np.uint8)

# 从份额图像中重建原始像素值
for i in range(h):
    for j in range(w):
        # 获取两个份额的值
        share1 = int(fx1[i, j])
        share2 = int(fx2[i, j])
        # 重建原始像素值
        recovered_pixel = ShamirReconstruction([(1, share1), (2, share2)], 2)
        recovered_image[i, j] = recovered_pixel % 256

# 保存重建的图像
cv2.imwrite('recovered_image.bmp', recovered_image)
print("重建的图像已保存为 recovered_image.bmp")